package edu.whu.demo.crawler.task;

import edu.whu.demo.crawler.httpUtil.HttpUtils;
import edu.whu.demo.domain.Activity;
import edu.whu.demo.exception.ActivityAdminException;
import edu.whu.demo.exception.ScheduleAdminException;
import edu.whu.demo.service.IScheduleService;
import edu.whu.demo.service.impl.ActivityServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.jsoup.nodes.Document;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DoTask {
    @Autowired
    ActivityServiceImpl abstractActivityService;
    @Autowired
    HttpUtils httpUtils;

    @Autowired
    IScheduleService scheduleService;

    //定时任务
/*    @Scheduled(fixedDelay = 24*60*60*1000)*/

    public void activityCrawler(){
        String url = "https://www.saikr.com/vs?page=";
        for (int i =1;i<=60;i++){
            String html = httpUtils.doGetHtml(url+i);
            parse(html);
        }
        System.out.println("数据抓取完成");
    }



    public void parse(String html){
        Document doc = Jsoup.parse(html);
        Elements element = doc.select(".body-wrap .event4-1-list-box li ");
        for (Element element1 : element) {
            //对于每一个元素提取相关信息之后存入对应项，然后存入数据库
            Activity activity = new Activity();

            activity.setType("竞赛");
            activity.setState("released");
            activity.setName(element1.select(".tit a").text());
            Elements elements = element1.select("p");
            try {
                activity.setBeginTime(elements.get(3).text().substring(5,15).replaceAll("\\.","-"));
                activity.setEndTime(elements.get(3).text().substring(18,28).replaceAll("\\.","-"));
            }catch (Exception e){
                activity.setBeginTime("时间待定");
                activity.setEndTime("时间待定");
            }
            activity.setInfo("主办方："+elements.get(0).text()+"\n"
                    +"竞赛级别："+elements.get(1).text()+"\n"
                    +"报名时间："+elements.get(2).text()+"\n"
                    +"比赛时间："+elements.get(3).text());
            activity.setPlace("未定");
            activity.setHostUid(-1L);
            activity.setStageCount(0);
            activity.setAddedTimes(0);
            activity.setStageNames("");


            Elements elementsDetailUrl = element1.select(".event-detail-manage-box a");
            String url = elementsDetailUrl.attr("href");//详情页Url
            String detail = httpUtils.doGetHtml(url);

            Document docDetail = Jsoup.parse(detail);
/*            Elements elementsDetail = docDetail.select(".sk-event4-1-detail-banner img");*/
            String imgSrc = docDetail.select(".sk-event4-1-detail-banner img").attr("src");

            Elements elements1 = docDetail.select(".text-body p");
            String text = "";
            for (Element elementP : elements1) {
                text = text+elementP.text()+"\r\n";
            }
            activity.setPic1(imgSrc);
            activity.setContent(text);

            Activity activityForUpdate = abstractActivityService.isPresent(activity);
            switch (dealUpdate(activityForUpdate)){
                case 1://需要更新
                    activity.setStageCount(activityForUpdate.getStageCount());
                    activity.setAddedTimes(activityForUpdate.getAddedTimes());
                    activity.setStageNames(activityForUpdate.getStageNames());
                    activity.setType(activityForUpdate.getType());
                    try {
                        abstractActivityService.updateActivity(activityForUpdate.getId(),activity);
                        scheduleService.updateSchedule(activityForUpdate.getId());
                    } catch (ActivityAdminException e) {
                        throw new RuntimeException(e);
                    } catch (ScheduleAdminException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 2://需要插入
                    activity.setStageCount(0);
                    activity.setAddedTimes(0);
                    activity.setStageNames("");
                    abstractActivityService.addActivity(activity);
                    break;
                case 3://需要删除
                    try {
                        abstractActivityService.deleteActivity(activityForUpdate.getId());
                    } catch (ActivityAdminException e) {
                        throw new RuntimeException(e);
                    }
                    break;
            }

        }
    }



    private int dealUpdate(Activity activity){
        if (activity!=null) {
            String endTime = activity.getEndTime();

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf1.parse(endTime.replaceAll("\\.","-"));
            } catch (ParseException e) {
                return 1;
            }
            long endDate = date.getTime();
            long nowDate;
            Date dateNow = new Date();
            try {
                Date date1 = sdf1.parse(sdf1.format(dateNow));
                nowDate =  date1.getTime();
            } catch (ParseException e) {
                return 1;
            }
            if (endDate>=nowDate){
                return 1;
            }else {
                return 3;
            }
        }else {
            return 2;
        }
    }
}
